package cn.gailvlun.gll.presentation.login.viewmodel

import cn.gailvlun.gll.databinding.ActivityPhoneBindingBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.NullSubscriber
import cn.gailvlun.gll.net.login.BindMobileReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.login.CaptchaActivity
import cn.gailvlun.gll.presentation.login.CountDownTimerWrapper
import cn.gailvlun.gll.presentation.login.FromActivityEnum
import cn.gailvlun.gll.util.*


class PhoneBindingViewModel(val activity: BaseActivity, private val mBinding: ActivityPhoneBindingBinding) : BaseViewModel(activity) {


    
    fun onNext() {

        val phoneNumber = mBinding.cetPhone.text.toString().trim()
        

        if (IsEmpty.string(phoneNumber)) {
            ToastUtil.showShort("请填写手机号")
            return

        }






        val cc = countryNameAndCode.split(" ")[1]
        val phoneNumberWithCc = "$cc$phoneNumber"


        if (CountDownTimerWrapper.phoneNumberWithCc == null || !CountDownTimerWrapper.phoneNumberWithCc.equals(phoneNumberWithCc)) {
            
            CountDownTimerWrapper.phoneNumberWithCc = phoneNumberWithCc
            CountDownTimerWrapper.countDown = 60L
            CountDownTimerWrapper.cancel()
            sendCode(phoneNumberWithCc)

        } else {
            if (CountDownTimerWrapper.countDown == 60L) {
                sendCode(phoneNumberWithCc)
            } else {
                CaptchaActivity.openActivity(activity, FromActivityEnum.ThirdPartyActivity, CountDownTimerWrapper.phoneNumberWithCc!!, ProfileUtil.getUserId()!!, null)
            }
        }


    }

    private fun sendCode(phoneNumberWithCc: String) {
        val bindMobileReq = BindMobileReq()
        bindMobileReq.mobile = phoneNumberWithCc
        bindMobileReq.id = ProfileUtil.getUserId()!!

        val pd = DialogUtil.showIndeterminate(activity)
        HttpMethods.getLoginService()
                .bindMobile(bindMobileReq)
                .compose(RxUtil.applyNullScheduler())
                .subscribe(object : NullSubscriber() {
                    override fun onSuccess() {
                        pd.dismiss()
                        CountDownTimerWrapper.startOnlyOnce()
                        ToastUtil.showShort("验证码已发送，请查收短信")
                        CaptchaActivity.openActivity(activity, FromActivityEnum.ThirdPartyActivity, phoneNumberWithCc, ProfileUtil.getUserId()!!, null)

                    }

                    override fun onFailure(errMsg: String, code: Int) {
                        pd.dismiss()
                        ToastUtil.showShort(errMsg)

                    }

                })


    }
}